/**
 * 账户管理
 */
({
	launch : function() {
		var me = this;
		var perms = this.perms;
		var account = {
			browse:function() {
				var _this = this;
				var source = '<div></div>';
				var datagrid = $("<table></table>");
				var tools = $('<div></div>');
				if(perms.add) {
					var addButton = $('<a href="#" class="icon-add"></a>').appendTo(tools);
					addButton.click(function() {
						_this.add(datagrid);
						return false;
					});
				}
				if(perms.remove) {
					var rmButton = $('<a href="#" class="icon-remove"></a>').appendTo(tools);
					rmButton.click(function() {
						$.messager.confirm("请确认：", "确认要删除所选账户吗？", function(isOk) {
							if(isOk) {
								var items = datagrid.datagrid("getChecked");
								var ids = [];
								$(items).each(function() {
									ids.push(this.id);
								});
								$.messager.mask().text("操作执行中，请稍后……");
								$.post(me.ctx + "/manager/account/remove", {ids : ids}, function(data) {
									if(data.success) {
										rmButton.hide();
										datagrid.datagrid("reload");
									}
									$.messager.mask('close');
								}, "json");							
							}
						});
						return false;
					});
				}
				var win = me.createWindow(source, {
					title:"账户管理",
					width:600,
					height:300,
					tools : tools
				});
				
				var columns = [
				        {field : 'id', title : '账户编号', width : 120, align : 'center', checkbox : true},
				        {field : 'account', title : '账户', width : 120},
				        {field : 'name', title : '用户名', width : 120},
				        {field : 'status', title : '状态', align : 'center', formatter : function(val, row) {
				        	return val == '1' ? "<a href='#' title='点击禁用'>启用</a>" : "<a href='#' title='点击启用'>禁用</a>";
				        }},
				        {field:'createtime', title:'创建时间', width:150, align:'center'}
				    ];
				if(perms.edit) {
					columns.push({
						field:'edit_button', title:"编辑", align:'center', formatter: function(value, row, index){
				        	return '<a class="l-btn l-btn-small l-btn-plain"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text l-btn-empty">&nbsp;</span><span class="l-btn-icon icon-edit">&nbsp;</span></span></a>';
					}});
				}
				if(perms.roles) {
					columns.push({
						field : 'role_button', title : '分配角色', align:'center', formatter: function(value, row, index){
				        	return '<a class="l-btn l-btn-small l-btn-plain"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text l-btn-empty">&nbsp;</span><span class="l-btn-icon icon-permissions">&nbsp;</span></span></a>';
					}});
				}
				datagrid.appendTo(win);
				datagrid.datagrid({
					fit : true,
					url : me.ctx + "/manager/account/browse",
					pagination : true,
					pageSize : 10,
					selectOnCheck : false,
					checkOnSelect : false,
					singleSelect : true,
				    columns : [columns],
				    onClickCell : function(index, field, value) {
				    	var rows = datagrid.datagrid("getRows");
				    	if(field === "edit_button") {
				    		_this.edit(datagrid, rows[index]);
				    	} else if(field === "role_button") {
				    		role.manager(rows[index]);
				    	}
				    },
				    onCheckAll : function(rows) {
				    	if(rows.length > 0 && perms.remove) {
				    		rmButton.show();
				    	}
				    },
				    onUncheckAll : function(rows) {
				    	if(perms.remove) {
				    		rmButton.show();
				    	}
				    },
				    onCheck : function(index, row) {
				    	if(perms.remove) {
				    		rmButton.show();
				    	}
				    },
				    onUncheck : function(index, row) {
				    	if(perms.remove && $(this).datagrid("getChecked").length < 1) {
				    		rmButton.hide();
				    	}
				    },
				    onLoadSuccess : function() {
				    	if(perms.remove) {
				    		rmButton.hide();
				    	}
				    }
				});
				
			},
			add:function(datagrid) {
				var _this = this;
				var footer = $('<div style="padding:5px;text-align:right;"></div>');
				var win = me.createWindow('<div></div>', {
					title:"账户添加",
					width:300,
					height:220,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
				form.form({
					url : me.ctx + "/manager/account/create",
					success: function(data){
						$.messager.mask("close");
				        var data = eval('(' + data + ')');
				        if (data.success){
				        	datagrid.datagrid("options").pageNumber = 1;
				            datagrid.datagrid("reload");
				            win.window("close");
				            $.messager.alert('提示：', "账户添加成功！", "info");
				        } else {
				        	$.messager.alert('提示：', "账户已存在！", "info");
				        }
				    }
				});
				var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
				var row = table.row();
				row.cell("账　　户：", {width:"60px"});
				var field = $('<input type="text" name="account" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['maxlength[50]']
				});
				
				row = table.row();
				row.cell("用户名称：");
				field = $('<input type="text" name="name" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['maxlength[50]']
				});
				row = table.row();
				row.cell("密　　码：");
				var password = field = $('<input id="account_password" type="password" name="password" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['minlength[6]']
				});
				row = table.row();
				row.cell("确认密码：");
				field = $('<input type="password" name="confirmpassword" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['password["#account_password"]']
				});
				row = table.row();
				row.cell("是否启用：");
				var id1 = uuid.create();
				var id0 = uuid.create();
				field = $('<span><input type="radio" id="'+ id1 +'" name="status" value="1" checked /><label for="'+id1+'">启用</label><input id="'+id0+'" type="radio" name="status" value="0" /><label for="'+id0+'">禁用</label></span>');
				var cell = row.cell(field);
				var saveButton = $('<a href="#">提交</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						if(form.form("validate")) {
							$.messager.mask().text("操作执行中，请稍后……");
							form.form("submit");
						}
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
			},
			edit:function(datagrid, account) {
				account.password = "";
				var _this = this;
				var footer = $('<div style="padding:5px;text-align:right;"></div>');
				var win = me.createWindow('<div></div>', {
					title:"账户编辑",
					width:300,
					height:220,
					resizable:false,
					minimizable:false,
					maximizable:false,
					modal:true,
					footer:footer
				});
				var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
				form.form({
					url : me.ctx + "/manager/account/update",
					success: function(data){
						$.messager.mask("close");
				        var data = eval('(' + data + ')');
				        if (data.success){
				        	datagrid.datagrid("options").pageNumber = 1;
				            datagrid.datagrid("reload");
				            win.window("close");
				            $.messager.alert('提示：', "账户更新成功！", "info");
				        } else {
				        	$.messager.alert('提示：', "已有账户在使用中，无法启用！", "info");
				        }
				    }
				});
				var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
				var row = table.row();
				row.cell("账　　户：", {width:"60px"});
				var fieldContainer = row.cell(account.account);
				$('<input type="hidden" name="id" /><input type="hidden" name="account" />').appendTo(fieldContainer);
				
				row = table.row();
				row.cell("用户名称：");
				var field = $('<input type="text" name="name" />');
				row.cell(field);
				field.textbox({
					required: true,
					validType : ['maxlength[50]']
				});
				row = table.row();
				row.cell("密　　码：");
				var pid = uuid.create();
				var password = field = $('<input id="'+pid+'" type="password" name="password" />');
				row.cell(field);
				field.textbox({
					validType : ['minlength[6]']
				});
				row = table.row();
				row.cell("确认密码：");
				field = $('<input type="password" name="confirmpassword" />');
				row.cell(field);
				field.textbox({
					validType : ['password["#'+pid+'"]']
				});
				row = table.row();
				row.cell("是否启用：");
				var id1 = uuid.create();
				var id0 = uuid.create();
				field = $('<span><input type="radio" id="'+ id1 +'" name="status" value="1" checked /><label for="'+id1+'">启用</label><input id="'+id0+'" type="radio" name="status" value="0" /><label for="'+id0+'">禁用</label></span>');
				var cell = row.cell(field);
				var saveButton = $('<a href="#">提交</a>').appendTo(footer);
				saveButton.linkbutton({
					iconCls : 'icon-ok',
					onClick : function() {
						if(form.form("validate")) {
							$.messager.mask().text("操作执行中，请稍后……");
							form.form("submit");
						}
						return false;						
					}
				});
				footer.append("&nbsp;");
				var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
				cancelButton.linkbutton({
					iconCls: 'icon-cancel',
					onClick: function(){
						win.window("close");
						return false;						
					}
				});
				form.form("load", account);
			}
		};
		var role = {
			manager : function(account) {
				$.post(me.ctx + "/manager/account/roles", {id:account.id}, function(data) {
					var footer = $('<div style="padding:5px;text-align:right;"></div>');
					var win = me.createWindow('<div></div>', {
						title:"角色分配",
						width:300,
						height:140,
						resizable:false,
						minimizable:false,
						maximizable:false,
						modal:true,
						footer:footer
					});
					var form = $('<form style="width:100%;" method="post"></form>').appendTo(win);
					form.form({
						url : me.ctx + "/manager/account/alloc",
						success: function(data){
							$.messager.mask("close");
					        var data = eval('(' + data + ')');
					        if (data.success){
					            win.window("close");
					            $.messager.alert('提示：', "角色分配成功！", "info");
					        } else {
					        	$.messager.alert('提示：', data.message, "info");
					        }
					    }
					});
					var table = $('<table width="100%" class="form-table"></table>').appendTo($('<div style="padding:5px 5px;"></div>').appendTo(form));
					var row = table.row();
					row.cell("账　　户：", {width:"60px"});
					var fieldContainer = row.cell(account.account);
					$('<input type="hidden" name="id" />').appendTo(fieldContainer);
					
					row = table.row();
					row.cell("用户名称：");
					row.cell(account.name);
					row = table.row();
					row.cell("角　　色：");
					var source = '<select name="role_ids" style="width:70%;"></select>';
					var field = $(source);
					row.cell(field);
					field.combobox({
					    required:true,
					    multiple:true,
						panelHeight:'auto',
					    valueField:'id',
					    textField:'name',
					    data:data.roles
					});
					
					var saveButton = $('<a href="#">提交</a>').appendTo(footer);
					saveButton.linkbutton({
						iconCls : 'icon-ok',
						onClick : function() {
							if(form.form("validate")) {
								$.messager.mask().text("操作执行中，请稍后……");
								form.form("submit");
							}
							return false;						
						}
					});
					footer.append("&nbsp;");
					var cancelButton = $('<a href="#">取消</a>').appendTo(footer);
					cancelButton.linkbutton({
						iconCls: 'icon-cancel',
						onClick: function(){
							win.window("close");
							return false;						
						}
					});
					account.role_ids = data.own;
					form.form("load", account);
				}, "json");
			}
		};
		account.browse();
	}
})